package dao;

import entity.Userinfo;

import java.sql.SQLException;
import java.util.List;

public class UserinfoDao extends BaseDao{
    /**
     * 新增用户
     */
    public boolean addUser(Userinfo user) throws SQLException {
        String sql = "insert into userinfo (username,gender,nickname,autograph,password) values (?,?,?,?,?)";
        int i = executeUpdate(sql, user.getUsername(), user.getGender(),
                user.getNickname(), user.getAutograph(), user.getPassword());
        return i > 0;
    }

    /**
     * 登录：根据用户名和密码查询用户，若存在，返回用户对象，否则返回null
     */
    public Userinfo login(String username, String password) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        String sql = "select * from userinfo where username=? and password=?";
        List<Userinfo> list = executeQuery(Userinfo.class, sql, username, password);
        if (list.isEmpty()) {
            return null;
        }else{
            return list.get(0);
        }
    }

    /**
     * 根据id查询用户
     */
    public Userinfo getUserById(String id) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        String sql = "select * from userinfo where id=?";
        List<Userinfo> list = executeQuery(Userinfo.class, sql, id);
        if (list.isEmpty()) {
            return null;
        }else {
            return list.get(0);
        }
    }
}
